<template>
  <ele-modal :form="true" :width="400" :title="data ? '编辑租户' : '新增租户'" position="center" v-model="visible"
    @open="handelOpen" @close="handelClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
      <el-form-item label="租户名称:" prop="name">
        <el-input v-model.trim="form.name" clearable></el-input>
      </el-form-item>
      <el-form-item label="系统标题:" prop="shortName">
        <el-input v-model.trim="form.shortName" clearable></el-input>
      </el-form-item>
      <el-form-item label="租户编码:" prop="code">
        <el-input v-model.trim="form.code" clearable></el-input>
      </el-form-item>
      <el-form-item label="排序:" prop="sort">
        <el-input-number v-model="form.sort" :min="0" :value-on-clear="0" />
      </el-form-item>
      <el-form-item label="租户logo:" prop="logo">
        <div>
          <input type="file" style="display: none" ref="fileInputRef" @change="handleFileChange" />
          <el-button v-if="!form.logo" type="primary" size="small" @click="showFileInput">
            点击上传
          </el-button>
          <img v-else style="width: 80px; height: 80px" :src="form.logo" fit="fill" @click="showFileInput" />
        </div>
      </el-form-item>
      <el-form-item label="租户状态:" prop="status">
        <el-switch v-model="form.status" class="ml-2" inline-prompt
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" active-text="启用" inactive-text="禁用"
          active-value="1" inactive-value="0" />
      </el-form-item>
      <el-form-item label="备注说明:" prop="comment">
        <el-input v-model="form.comment" style="width: 600px" :rows="2" type="textarea" placeholder="请输入备注" />
      </el-form-item>

    </el-form>
    <template #footer>
      <el-button type="primary" :loading="loading" @click="save">提交</el-button>
    </template>
  </ele-modal>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue"
import { EleMessage } from "ele-admin-plus";
import type { FormInstance, FormRules } from 'element-plus';
import { useFormData } from '@/utils/use-form-data';
import { add, edit } from '@/api/system/SysTenant';
import type { SysTenant, AddSysTenant } from "@/api/system/SysTenant/model.ts";


const props = defineProps<{
  data: SysTenant | null
}>()

const emit = defineEmits<{
  (e: 'reload'): void
}>()

const fileInputRef = ref<HTMLInputElement | null>(null);
const formRef = ref<FormInstance | null>(null);
const loading = ref<boolean>(false)
const visible = defineModel({ type: Boolean });
const { form, assignFields, resetFields } = useFormData<AddSysTenant>({
  comment: '',    // 备注说明，默认为空字符串
  status: '1',    // 状态，默认为 '1'（正常）
  name: '',       // 租户名称，默认为空字符串
  shortName: '',  // 系统标题，默认为空字符串
  logo: '',       // 租户logo，默认为空字符串
  code: '',       // 租户编码，默认为空字符串
  sort: 0         // 排序序号，默认为 0
})

const rules = reactive<FormRules>({
  name: [
    {
      required: true,
      message: '请输入模块名称',
      type: 'string',
      trigger: 'blur'
    }
  ],
  shortName: [
    {
      required: true,
      message: '请输入系统标题',
      type: 'string',
      trigger: 'blur'
    }
  ],
  code: [
    {
      required: true,
      message: '请输入租户编码',
      type: 'string',
      trigger: 'blur'
    }
  ]
});

const showFileInput = () => {
  fileInputRef.value?.click();
};

const handleFileChange = (event: any) => {
  const file = event.target.files[0];
  const reader = new FileReader();
  reader.onload = (e) => {
    form.logo = e.target?.result as string;
  };
  reader.readAsDataURL(file);
};


const save = () => {
  formRef.value?.validate().then(async () => {
    loading.value = true
    const res = props.data ? await edit({ ...form, id: props.data.id }) : await add(form)
    loading.value = false
    if (res.code == 200) {
      EleMessage.success('成功提交')
      emit('reload')
      visible.value = false
    } else {
      EleMessage.error(res.message)
      return
    }
  })
}

const handelOpen = () => {
  if (props.data) {
    assignFields(props.data)
    form.sort = Number(form.sort)
  }
}

const handelClose = () => {
  resetFields()
  formRef.value?.resetFields()
}

</script>

<style scoped></style>
